<template>
  <div>
    <div class="headerSty1" style="margin: 20px 0 10px;" :loading="loading">
      <div>
        <el-form label-width="150px" ref="elForm" :model="dataForm" :rules="rules">
          <el-row>
            <el-col :span="24">
              <el-form-item label-width="10px">
                <div class="headerLeftSty">
                  <div class="navSty"></div>
                  <div class="textSty1" style="margin-left: 10px;">基本信息</div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="企业名称" prop="name">
                <el-input v-model="dataForm.name" placeholder="请输入" clearable :style='{ "width": "100%" }'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="企业简称" prop="abbreviation">
                <el-input v-model="dataForm.abbreviation" placeholder="请输入" clearable :style='{ "width": "100%" }'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="企业电话" prop="phoneNumber">
                <el-input v-model="dataForm.phoneNumber" placeholder="请输入" clearable :style='{ "width": "100%" }'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="企业类型" prop="type">
                <el-select v-model="dataForm.type" placeholder="请选择" :style='{ "width": "100%" }'>
                  <el-option v-for="(item, index) in enterpriseTypeList" :key="index" :label="item.dictLabel"
                    :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="所属行业" prop="industry">
                <el-select v-model="dataForm.industry" placeholder="请选择" :style='{ "width": "100%" }'>
                  <el-option v-for="(item, index) in enterpriseIndustryList" :key="index" :label="item.dictLabel"
                    :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="所在地区" prop="mapAddress">
                <el-input v-model="dataForm.mapAddress" @focus="changeOpenState" placeholder="请选择"
                  :style='{ "width": "100%" }'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="详细地址" prop="address">
                <el-input v-model="dataForm.address" placeholder="请输入" clearable :style='{ "width": "100%" }'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="邮政编码" prop="postcode">
                <el-input v-model="dataForm.postcode" placeholder="请输入" clearable :style='{ "width": "100%" }'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="企业传真" prop="fax">
                <el-input v-model="dataForm.fax" placeholder="请输入" clearable :style='{ "width": "100%" }'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="企业网址" prop="website">
                <el-input v-model="dataForm.website" placeholder="请输入" clearable :style='{ "width": "100%" }'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="成立时间" prop="establishmentTime">
                <el-date-picker clearable v-model="dataForm.establishmentTime" type="date" value-format="yyyy-MM-dd"
                  placeholder="请选择成立时间" style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label-width="10px">
                <div class="headerLeftSty">
                  <div class="navSty"></div>
                  <div class="textSty1" style="margin-left: 10px;">公司Logo
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="公司logo" prop="logo">
                <ImageUpload v-model="dataForm.logo" :limit="1" :fileSize="10" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label-width="10px">
                <div class="headerLeftSty">
                  <div class="navSty"></div>
                  <div class="textSty1" style="margin-left: 10px;">企业联系人
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="企业联系人" prop="contactPerson">
                <el-input v-model="dataForm.contactPerson" placeholder="请输入" clearable :style='{ "width": "100%" }'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="用户性别" prop="sex">
                <el-select v-model="dataForm.sex" placeholder="请选择性别">
                  <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="职务" prop="post">
                <el-input v-model="dataForm.post" placeholder="请输入" clearable :style='{ "width": "100%" }'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="企业联系人电话号码" prop="contactPersonPhone">
                <el-input v-model="dataForm.contactPersonPhone" placeholder="请输入" clearable
                  :style='{ "width": "100%" }'>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="企业联系人邮箱" prop="contactPersonEmail">
                <el-input v-model="dataForm.contactPersonEmail" placeholder="请输入" clearable
                  :style='{ "width": "100%" }'>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item>
              <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">保存</el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
    </div>
    <el-dialog :visible.sync="openMap" width="80%" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false" :show-close="false">
      <div class="mapSty">
        <div class="inMapSty">
          <span style="width: 5rem;">当前位置:</span>
          <el-input type="text" v-model="mapText" id="searchInput" @input="placeAutoInput('searchInput')"
            @keyup.delete.native="deletePlace('searchInput')" />
        </div>
        <!--地址模糊搜索子组件-->
        <place-search class="place-wrap" ref="placeSearch" v-if="resultVisible" :result="result" :left="offsetLeft"
          :top="offsetTop" :width="inputWidth" :height="inputHeight" @getLocation="getPlaceLocation"></place-search>
        <div>
          <div id="allMap" class="allMap"></div>
        </div>

      </div>
      <span slot="footer" class="dialog-footer">
        <div style="display: flex;justify-content: space-between;">
          <div v-if="formattedAddress">当前定位: <i class="el-icon-location-outline"></i>{{ formattedAddress }}</div>
          <div style="flex: 1;">
            <el-button @click="openMap = false">取 消</el-button>
            <el-button type="primary" @click="updateMapAddress">确 定</el-button>
          </div>
        </div>
      </span>


    </el-dialog>
  </div>
</template>
<script>


import { managerDetail, putEnterprise } from "@/api/enterprise/index";

import { getDicts as getDicts } from '@/api/system/dict/data'
import placeSearch from '@/components/PlaceSearch'
export default {
  dicts: ["sys_normal_disable", "sys_user_sex"],
  data() {
    const fileMustUpload1 = (rule, value, callback) => {
      if (
        this.dataForm.logo == undefined ||
        this.dataForm.logo == null ||
        this.dataForm.logo == ""
      ) {
        callback("请上传公司Logo");
      } else {
        callback();
      }
    };
    return {
      // 表单校验
      rules: {
        name: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
        abbreviation: [{ required: true, message: '请输入企业简称', trigger: 'blur' }],
        phoneNumber: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择企业类型",
            trigger: "change",
          },
        ],
        industry: [
          {
            required: true,
            message: "请选择所属行业",
            trigger: "change",
          }
        ],
        technicalDirectorIdCard: [
          { validator: fileMustUpload1, trigger: "change" },
        ],
        contactPerson: [
          {
            required: true,
            message: '请输入企业联系人姓名',
            trigger: 'blur'
          },
        ],
        contactPersonPhone: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      btnLoading: false,
      loading: false,
      dataForm: {},
      enterpriseTypeList: [],
      enterpriseIndustryList: [],
      // 高德
      openMap: false,
      inputId: '', // 地址搜索input对应的id
      result: [], // 地址搜索结果
      resultVisible: false, // 地址搜索结果显示标识
      inputWidth: 0, // 搜索框宽度
      inputHeight: 0, // 搜索框高度
      offsetLeft: 0, // 搜索框的左偏移值
      offsetTop: 0, // 搜索框的上偏移值
      sNameMap: null,  // 上车地点地图选址
      sNameMapShow: false,  // 上车地点地图选址显示
      mapText: "",
      formattedAddress: '',
      longitude: 104.065837,
      latitude: 30.657349,

    }
  },
  created() {
    this.getList()
    // 获取行业
    getDicts('enterprise_industry').then(res => {
      this.enterpriseIndustryList = res.data
    })
    // 获取企业类型
    getDicts('enterprise_type').then(res => {
      this.enterpriseTypeList = res.data
    })
  },
  mounted() {
    // document添加onclick监听，点击时隐藏地址下拉浮窗
    document.addEventListener("click", this.hidePlaces, false);
    // window添加onresize监听，当改变窗口大小时同时修改地址下拉浮窗的位置
    window.addEventListener("resize", this.changePos, false)
  },
  beforeDestroy() {
    document.removeEventListener("click", this.hidePlaces, false);
  },
  components: {
    'place-search': placeSearch
  },

  methods: {
    getList() {
      this.loading = true
      managerDetail().then(res => {
        this.dataForm = res.data
        this.loading = false
      })
    },

    // 表单提交
    dataFormSubmit(type) {
      this.$refs['elForm'].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          putEnterprise(this.dataForm).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.btnLoading = false
            this.getList()
          })
        }
      })
    },
    // 展开地图
    changeOpenState(event) {
      this.openMap = true;
      if (this.dataForm.longitude) {
        this.longitude = this.dataForm.longitude;
        this.latitude = this.dataForm.latitude;
        this.formattedAddress = this.dataForm.mapAddress
      }
      this.$nextTick(() => {
        this.initMap()
      });
    },

    initMap() {
      this.sNameMap = new AMap.Map('allMap', {
        zoom: 16,
        scrollWheel: false,
        center: [this.longitude, this.latitude]
      });
      AMapUI.loadUI(['misc/PositionPicker'], (PositionPicker) => {
        let positionPicker = new PositionPicker({
          mode: 'dragMap',
          map: this.sNameMap
        });
        positionPicker.start();
        this.sNameMap.addControl(new AMap.ToolBar({
          liteStyle: true
        }));
      });
      this.sNameMap.on("click", this.clickMapHandler);
    },
    placeAutoInput(inputId) {
      let currentDom = document.getElementById(inputId);// 获取input对象
      let keywords = currentDom.value;
      if (keywords.trim().length === 0) {
        this.resultVisible = false;
      }
      AMap.plugin('AMap.Autocomplete', () => {
        // 实例化Autocomplete
        let autoOptions = {
          city: '全国'
        };
        let autoComplete = new AMap.Autocomplete(autoOptions); // 初始化autocomplete
        // 开始搜索
        autoComplete.search(keywords, (status, result) => {
          // 搜索成功时，result即是对应的匹配数据
          if (result.info === 'OK') {
            let sizeObj = currentDom.getBoundingClientRect(); // 取得元素距离窗口的绝对位置
            this.inputWidth = currentDom.clientWidth;// input的宽度
            this.inputHeight = currentDom.clientHeight + 2;// input的高度，2是上下border的宽
            // input元素相对于页面的绝对位置 = 元素相对于窗口的绝对位置
            this.offsetTop = sizeObj.top + this.inputHeight; // 距顶部
            // this.offsetTop = 36; // 距顶部
            this.offsetLeft = sizeObj.left; // 距左侧
            this.result = result.tips;
            this.inputId = inputId;
            this.resultVisible = true;
          }
        })
      })
    },
    // 点击地图选点
    clickMapHandler(e) {
      this.pickAddress('searchInput', e.lnglat.lng, e.lnglat.lat)
    },
    // 隐藏搜索地址下拉框
    hidePlaces(event) {
      let target = event.target;
      // 排除点击地址搜索下拉框
      if (target.classList.contains("address")) {
        return;
      }
      this.resultVisible = false;
    },
    // 修改搜索地址下拉框的位置
    changePos() {
      if (this.inputId && this.$refs['placeSearch']) {
        let currentDom = document.getElementById(this.inputId);
        let sizeObj = currentDom.getBoundingClientRect(); // 取得元素距离窗口的绝对位置
        // 元素相对于页面的绝对位置 = 元素相对于窗口的绝对位置
        let inputWidth = currentDom.clientWidth;// input的宽度
        let inputHeight = currentDom.clientHeight + 2;// input的高度，2是上下border的宽
        let offsetTop = sizeObj.top + inputHeight; // 距顶部
        let offsetLeft = sizeObj.left; // 距左侧
        this.$refs['placeSearch'].changePost(offsetLeft, offsetTop, inputWidth, inputHeight);
      }
    },
    // 获取子组件返回的位置信息
    getPlaceLocation(item) {
      if (item) {
        this.resultVisible = false;
        if (item.location && item.location.getLat()) {
          this.pickAddress(this.inputId, item.location.getLng(), item.location.getLat());
        } else {
          this.geocoder(item.name, this.inputId);
        }
      }
    },
    // 地图选址
    pickAddress(inputId, lon, lat) {
      this.sNameMap = new AMap.Map('allMap', {
        zoom: 16,
        scrollWheel: false,
        center: [lon, lat]
      });
      this.sNameMap.on("click", this.clickMapHandler);
      if (inputId === "searchInput") {
        this.sNameMapShow = true;
        AMapUI.loadUI(['misc/PositionPicker'], (PositionPicker) => {
          let positionPicker = new PositionPicker({
            mode: 'dragMap',
            map: this.sNameMap
          });
          positionPicker.on('success', (positionResult) => {
            this.dataForm.latitude = positionResult.position.lat;
            this.dataForm.longitude = positionResult.position.lng;
            this.formattedAddress = positionResult.address;
            this.mapText = positionResult.address
          });
          positionPicker.on('fail', (positionResult) => {
            this.$message.error("地址选取失败");
          });
          positionPicker.start();
          this.sNameMap.addControl(new AMap.ToolBar({
            liteStyle: true
          }));
        });
      }
    },
    // 地理编码
    geocoder(keyword, inputValue) {
      let geocoder = new AMap.Geocoder({
        radius: 1000 //范围，默认：500
      });
      //地理编码,返回地理编码结果
      geocoder.getLocation(keyword, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          let geocode = result.geocodes;
          if (geocode && geocode.length > 0) {
            if (inputValue === "sname") {
              this.dataForm.latitude = geocode[0].location.getLat();
              this.dataForm.longitude = geocode[0].location.getLng();
              this.formattedAddress = keyword;
              // 如果地理编码返回的粗略经纬度数据不需要在地图上显示，就不需要调用地图选址，且要隐藏地图
              // this.pickAddress("sname", geocode[0].location.getLng(), geocode[0].location.getLat());
              this.sNameMapShow = false;
            }
          }
        }
      });
    },
    // 做删除操作时还原经纬度并验证字段
    deletePlace(inputId) {
      if (inputId === "searchInput") {
        this.longitude = 104.065837;
        this.latitude = 30.657349;
      }
    },
    // 改变地图地址
    updateMapAddress() {
      this.dataForm.mapAddress = this.formattedAddress;
      this.openMap = false;
    },
  }
}
</script>

<style lang="scss" scoped>
.map-wrapper .map-self {
  height: 150px;
  width: 300px;
}

.headerSty {
  display: flex;
  justify-content: space-between;
  width: 97%;

  .headerLeftSty {
    display: flex;
    align-items: center;

    .textSty {
      margin-left: 8px;
      font-size: 16px;
      font-weight: 700;
    }


  }

}

#panel {
  position: absolute;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 36px;
  right: 0;
  width: 280px;
}

.mapSty {
  width: 100%;
  height: 450px;
  position: relative;
}


.headerSty1 {
  width: 97%;

  .headerLeftSty {
    display: flex;
    align-items: center;

    .textSty1 {
      margin-left: 8px;
      font-size: 14px;
      font-weight: 700;
    }

    .textSty {
      margin-left: 8px;
      font-size: 16px;
      font-weight: 600;
    }
  }

}

.rickSty {
  border: 1px solid #999;
  height: 300px;
  overflow-y: auto;
}

.btnAllSty {
  background: #7915F5;
  color: #fff;
  border: none;
}


.navSty {
  height: 15px;
  width: 5px;
  background: rgb(90, 156, 248);
}


.contSty {
  display: flex;

  .contLeftSty {
    height: 80px;
    width: 5px;
    background: rgb(90, 156, 248);
  }

  .allBlo {
    margin-left: 5px;
  }

  .LastBlockSty {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 132px;
    height: 30px;
    background: white;
    border-radius: 5px;
    color: rgb(90, 156, 248);
    border: 1px solid rgb(90, 156, 248);

    .el-icon-warning {
      color: rgb(90, 156, 248);
      font-weight: bolder;
      margin-right: 5px;
      font-size: 18px;
    }
  }

  .blockSty {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 132px;
    height: 30px;
    background: rgb(90, 156, 248);
    border-radius: 5px;
    color: white;

    .el-icon-check {
      color: white;
      font-weight: bolder;
      margin-right: 5px;
      font-size: 18px;
    }

    .el-icon-close {
      color: white;
      font-weight: bolder;
      margin-right: 5px;
      font-size: 18px;
    }
  }

  .lastTeSty {
    flex: 1;
    height: 120px;
    background: white;
    margin-left: 10px;
    border-radius: 5px;
    border: 1px solid rgb(90, 156, 248);
    overflow-y: auto;
  }
}

.text1 {
  font-size: 14px;
  font-weight: 500;
}

.text2 {
  font-size: 14px;
  color: #999;
}

.el-icon-arrow-right {
  color: rgb(90, 156, 248);
  font-weight: bolder;
  margin: 0 10px;
  font-size: 32px;
}

#allMap {
  width: 100%;
  height: 450px;
}

.inMapSty {
  width: 20rem;
  position: absolute;
  top: 0;
  right: 0;
  z-index: 999999;
  opacity: 0.8;
  display: flex;
  height: 36px;
  line-height: 36px;

}
</style>